package 线程池;

import sun.misc.Unsafe;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class 自行实现的线程池 {

    //阻塞队列：仓库
    private BlockingQueue<Runnable> queue;

    public 自行实现的线程池(int count, int capacity) {
        this.queue = new ArrayBlockingQueue<>(capacity);
        //线程池创建，就创建线程来不停取任务并执行
        for (int i = 0; i < count; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //不停的从仓库中取任务：如果取不到就等待
                    while (true){
                        try {
                            Runnable task = queue.take();
                            task.run();//执行任务
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }

    public void execute(Runnable task){
        try {
            queue.put(task);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        自行实现的线程池 pool = new 自行实现的线程池(5, 1000);
        pool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        });
    }
}
